class Solution:
    def maxDistance(self, nums1: list, nums2: list) -> int:
        def search(array, left, right, target):
            while left < right:
                mid = (left + right) // 2
                if array[mid] > target:
                    left = mid + 1
                else:
                    right = mid

            return right

        res = 0
        cursor = 0
        for j in range(len(nums2)):
            if nums2[j] >= nums1[cursor]:
                res = max(res, (j - cursor))
                continue
            i = search(nums1, cursor, min(j, len(nums1) - 1), nums2[j])
            if nums2[j] >= nums1[i]:
                res = max(res, (j - i))
                cursor = i
            else:
                cursor = min(i + 1, len(nums1) - 1)

        return res
